const url = "http://localhost:3000/todos";

window.onload = function() {
    initList();
};

async function initList() {
    // 1. 使用fetch发送列表请求
    const response = await fetch(url, {
        method: 'get'
    });

    // 2. 判断请求是否成功 response.ok <===> (response.status === 200)
    if(!response.ok) {
        throw new Error(`获取列表失败：${response.status}`);
    }
    
    // 3.解析后端返回的列表数据
    const listData = await response.json();

    // 4.判断数据是否存在并渲染列表页面
    if(listData) {
        renderTodoList(listData)
    }
}

function renderTodoList(list) {
    // 1. 过滤状态为todo的数据
    const todoList = list.filter(item => item.status === 'todo');

    // 2. 生成todo item的dom结构
    const todoElements = todoList.map(item => createTodoTaskItem(item));
    
    // 3. 获取要插入的todo list节点
    const todoTaskListElement = document.querySelector('#todo .task-list');
    
    // 4. 清空列表下的所有内容
    todoTaskListElement.innerHTML = '';

    // 5. 把生成好的li标签动态插入到ul中
    todoElements.forEach(element => todoTaskListElement.appendChild(element));
}

function createTodoTaskItem(item) {
    // 1. 生成li标签
    const liElement = document.createElement("li");
    liElement.classList.add("task-item");

    // 2. 生成task内容
    liElement.innerHTML = `<div class="task-content">
                        <h3>${item.title}</h3>
                        <p>${item.content}</p>
                    </div>
                    <div class="task-actions">
                        <button class="action-btn complete-btn" onclick="completeTask(${item.id})">
                            <span class="iconfont icon-duigou btn-icon"></span>
                            <span class="btn-text">完成</span>
                        </button>
                        <button class="action-btn delete-btn" onclick="deleteTask(${item.id})">
                            <span class="iconfont icon-fork btn-icon"></span>
                            <span class="btn-text">删除</span>
                        </button>
                    </div>`;
    return liElement;
}

async function completeTask(taskId) {
    // 1. 获取当前taskId的最新数据
    const taskData = await getTaskItemById(taskId);

    /**
     * {...taskData} <===> {id: taskData.id, title: taskData.title, ...}
     */
    
    // 2. 更新当前task的状态
    const response = await fetch(`${url}/${taskId}`, {
        method: 'put',
        body: JSON.stringify({
            ...taskData,
            status: 'done'
        })
    });

    if (!response.ok) {
        throw new Error(`更新失败：${response.status}`)
    }

    const data = await response.json();
    
    if (data) {
        initList();
    }
}

async function getTaskItemById(taskId) {
    // 1. 获取单个task item
    const response = await fetch(`${url}/${taskId}`);
    
    if (!response.ok) {
        throw new Error(`获取失败：${response.status}`)
    }

    return await response.json();
}

async function deleteTask(taskId) {
    const response = await fetch(`${url}/${taskId}`, {
        method: 'delete',
    });

    if (!response.ok) {
        throw new Error(`删除失败：${response.status}`)
    }

    const data = await response.json();
    
    if (data) {
        initList();
    }
}

async function searchTask(event) {
     const value = event.target.value;

     // 兼容搜索了内容后，删除了搜索的关键字
     if (!value) {
        initList();
        return;
     }

     const response = await fetch(`${url}?title=${value}`);

     if (!response.ok) {
        throw new Error(`搜索失败：${response.status}`)
     }

     const data = await response.json();
     renderTodoList(data);
}

async function addTodoTask() {
    const input = document.getElementById('add-input');
    if (!input.value) {
        alert("请输入待办标题");
        return;
    }

    const randomNumber = Math.random() * 100;
    const response = await fetch(`${url}`, {
        method: 'post',
        body: JSON.stringify({
            id: randomNumber.toString(),
            title: input.value,
            content: "动态添加",
            status: "todo"
        })
    });

    if (!response.ok) {
        throw new Error(`添加失败：${response.status}`)
    }

    const data = await response.json();
    
    if (data) {
        input.value = '';
        initList();
    }
}